`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 11/02/2016 12:29:12 PM
// Design Name: 
// Module Name: dac8811
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////

//    always@(posedge ui_addn_clk_0)  //provide daclk enable 
//      begin
//        if(daclkcnt<3'd1)
//          daclkcnt<=daclkcnt+3'b1;
//        else
//          daclkcnt<=3'd0; 
//      end    
 
//    wire daclken= (daclkcnt==3'd1);
//    assign daclk= (daclkcnt>3'b0); 

module dac8811
    (
     input userclk,
     output dacs,
     input daclken,
     input [16:0]dadata,
     output reg dasdi

    );

    parameter IDLE=2'b00;
    parameter START=2'b01;
    parameter DATATRANS=2'b11;
    parameter CSHIGH=2'b10;  

    reg [16:0] dadata_reg;
    reg [1:0] state;
    reg [4:0] bit;
    reg [1:0] cnt;
 initial begin dadata_reg=17'b0;bit=5'd16;dasdi=1'b0; end
 initial begin state=IDLE;cnt=2'b0; end
    

always@(posedge userclk)
  begin
   if(daclken)
     begin
//       if(dadata_reg[16:1]^dadata[16:1])
//         dadata_reg<=dadata;
//       else
//         dadata_reg<=dadata_reg;
       case(state)
         IDLE:
           begin 
             if(dadata_reg[0])
               state<=START;
             else
               state<=state;
             bit=5'd16;
           end
         START:
           begin 
             state<=DATATRANS;
             dasdi<=dadata_reg[bit];
             bit<=bit-5'd1;
           end
         DATATRANS:
           begin 
             if(bit>5'b0)
               begin
                 dasdi<=dadata_reg[bit];
                 bit<=bit-5'd1;
               end
             else
               begin
//                 dasdi<=dadata_reg[bit];
                 bit<=5'd16;
                 state<=CSHIGH;
                 dadata_reg[0]<=1'b0;
               end
           end
         CSHIGH:
           begin 
             if(cnt<=2'd1)
               begin
                 cnt<=cnt+1;
               end
             else
               begin
                 cnt<=2'b0;
                 state<=IDLE;
               end
           end 
       endcase  
   end // end if daclken
   else
     state<=state;
  end
 
 
 
 assign dacs=~(state==DATATRANS);
endmodule



